package dp;

/**
 * @description: 01背包问题
 * @author: wangjun
 * @create: 2022-05-06
 */
public class KnapsackProblem {

    public static void main(String[] args) {
        // 物品的重量
        int[] w = {1, 4, 3};
        int[] val = {1500, 3000, 2000};
        // 背包的容量
        int m = 4;
        // 物品个数
        int n = val.length;
        // v[i][j] 表示背包放入前i个物品容量为j的最大价值
        int[][] v = new int[n + 1][m + 1];
        // 记录加入背包的物品
        int[][] path = new int[n + 1][m + 1];
        for (int i = 0; i < n; i++) {
            // 将第一列设置为0
            v[i][0] = 0;
        }
        for (int i = 1; i < v[0].length; i++) {
            // 将第一行设置为0
            v[0][i] = 0;
        }

        for (int i = 1; i < v.length; i++) {
            for (int j = 1; j < v[0].length; j++) {
                // 物品容量大于背包容量
                if (w[i - 1] > j) {
                    v[i][j] = v[i - 1][j];
                } else {
                    if (v[i - 1][j] > val[i - 1] + v[i - 1][j - w[i - 1]]) {
                        v[i][j] = v[i - 1][j];
                    } else {
                        v[i][j] = val[i - 1] + v[i - 1][j - w[i - 1]];
                        path[i][j] = 1;
                    }
                }
            }
        }

        for (int i = 0; i < v.length; i++) {
            for (int j = 0; j < v[0].length; j++) {
                System.out.print(v[i][j] + " ");
            }
            System.out.println();
        }

        int p = path.length - 1;
        int q = path[0].length - 1;
        while (p > 0 && q > 0) {
            if (path[p][q] == 1) {
                System.out.printf("第%d个物品放入背包\n", p);
                q -= w[p - 1];
            }
            p--;
        }
    }



}